package com.wx.rabbitmq.returnlistener;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ReturnListener;
import com.wx.rabbitmq.MqConnection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static com.wx.rabbitmq.returnlistener.Consumer.EXCHANGE_DIREC_RETURN;

/**
 * @author wx
 * @Description: 生产者-return消息机制 returnlistener 处理一些不可路由的消息，
 * 不可路由消息是指制定的路由不存在或者路由key不存在，导致这个消息无法被消费，这是一个错误的消息
 * 在发送消息的时候能设置一个参数，参数名为Mandatory,
 * 1.Mandatory为true不可路由消息能通过监听器获取
 * 2.Mandatory为false，那么队列会自动删除错误消息，默认为false
 * @date 2018/11/23 002317:25
 */
public class Producer {

    public static void main(String[] agrs) throws IOException, TimeoutException {
        //1.获取connection
        Connection connection = MqConnection.getConnection();

        //2.通过connection创建一个Channel
        Channel channel = connection.createChannel();
        //3.指定我们的消息投递模式: 消息的确认模式
        channel.confirmSelect();
        //4. 通过Channel发送数据   exchange=交换机、 2 routingKey=队列对应的key、3 props = 消息装饰器、 4=消息体
        String routingKey = "return.save";
        String errRoutingKey = "err.save";
        String msg = "Hello RabbitMQ Send returnlistener message!";
        /**
         * 1.mandatory为true不可路由消息能通过监听器获取
         * 2.mandatory为false，那么队列会自动删除错误消息，默认为false
         */
        channel.basicPublish(EXCHANGE_DIREC_RETURN, routingKey, true, null, msg.getBytes());
        channel.basicPublish(EXCHANGE_DIREC_RETURN, errRoutingKey, true, null, msg.getBytes());

        //5.监听不可路由消息(异步)
        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange,
                                     String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.err.println("---------handle  return----------");
                System.err.println("replyCode: " + replyCode);
                System.err.println("replyText: " + replyText);
                System.err.println("exchange: " + exchange);
                System.err.println("routingKey: " + routingKey);
                System.err.println("properties: " + properties);
                System.err.println("body: " + new String(body));
            }
        });

        System.out.println("异步监听------------------------------");
    }

}
